package cn.tanghom.app.oa.controller;

import cn.tanghom.content.service.ArticleCategoryService;
import cn.tanghom.app.oa.model.Candidate;
import cn.tanghom.app.oa.model.Position;
import cn.tanghom.app.oa.model.Talent;
import cn.tanghom.app.oa.repository.CandidateRepository;
import cn.tanghom.app.oa.repository.EduExpRepository;
import cn.tanghom.app.oa.repository.TalentRepository;
import cn.tanghom.app.oa.repository.WorkExpRepository;
import cn.tanghom.app.oa.service.RecruitmentProcessService;
import cn.tanghom.app.system.model.User;
import cn.tanghom.support.id.IDWorker;
import cn.tanghom.support.page.Pager;
import cn.tanghom.support.utils.CommonUtils;
import cn.tanghom.support.web.ContextHolder;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.*;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

import java.util.*;

import static cn.tanghom.support.web.BaseController.THEME_PATH;

/**
 * 单个人才和单个职位匹配和面试流程
 *
 * @author tanghom
 */
@Controller
@RequestMapping("/oa/interview")
public class InterviewController {	
	
	@Autowired
	private MongoOperations destination;
	
	@Resource
    private ArticleCategoryService articleCategoryService;
	
	@Autowired
	TalentRepository talentRepository;
	
	@Autowired
	WorkExpRepository workExpRepository;
	
	@Autowired
	EduExpRepository eduExpRepository;
  
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private HistoryService historyService;
    @Resource
    private ProcessEngine processEngine;
    @Resource
    private IdentityService identityService;
    @Resource
    private RecruitmentProcessService matchService;    
    @Resource
    private CandidateRepository candidateRepository;
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String showMatchList(Model model) {    	
    	
    	final Subject subject = SecurityUtils.getSubject();
    	String username = (String) subject.getPrincipal();   
        
        return THEME_PATH+"/oa/interview/match-list";
    }
    /**
     * 只返回candidate中进入面试的人才
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public List<Candidate> getMatchList(Model model) {
    	List<Candidate> listDto;
    	PageRequest pager = new PageRequest(0,10);
        Page<Candidate> page;
        //Long id = Long.parseLong((String)model.asMap().get("id"));
        String title = "java";
    	page = candidateRepository.findAll(pager);    	
    	
        listDto = page.getContent();                 
        return listDto;
    }
    
    
    //给职位推荐人才，是人工页面，然后开启这个人才的面试流程
    @RequestMapping(value = "/apply",method =RequestMethod.GET)
    public ModelAndView createForm() {
        ModelAndView mav = new ModelAndView(THEME_PATH + "/oa/interview/apply");
        mav.addObject("position", new Position());
        return mav;
    }

    //收到推荐对，启动面试流程
    @RequestMapping(value = "/apply", method =RequestMethod.POST)
    @ResponseBody
    public String apply(Candidate cndi) {
        try {
            User loger = ContextHolder.getUser();
            cndi.setUserId(loger.getId());
            cndi.setCreateTime(new Date());
            Map<String, Object> variables = new HashMap<String, Object>();
            ProcessInstance processInstance = matchService.startWorkflow(cndi, variables);
            return CommonUtils.msgCallback(true, "流程已启动", "", processInstance.getId());
        } catch (FlowableException e) {
            if (e.getMessage().indexOf("no processes deployed with key") != -1) {
                return CommonUtils.msgCallback(false, "系统内部错误，请联系管理员（没有部署流程，请在[工作流]->[流程管理]页面点击<重新部署流程>），" + e.getMessage(), "", null);
            } else {
                return CommonUtils.msgCallback(false, "系统内部错误,请联系管理员（启动请假流程失败），" + e.getMessage(), "", null);
            }
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "系统内部错误,请联系管理员，" + e.getMessage(), "", null);
        }
    }    
    

    /**
     * 面试任务列表
     *
     */
    @RequestMapping(value = "/task/list")
    public ModelAndView taskList(Long pageNo) {
        ModelAndView mav = new ModelAndView(THEME_PATH + "/oa/interview/task-list");
        // 根据当前人的ID查询
        List<Candidate> leaves = new ArrayList<Candidate>();
        Pager<Candidate> page = new Pager<Candidate>();
        page.setIndex(pageNo);
        User loger = ContextHolder.getUser();
        TaskQuery taskQuery = taskService.createTaskQuery().processDefinitionKey("interviewProcess").taskCandidateOrAssigned(loger.getLoginName());
        List<Task> tasks = taskQuery.listPage(page.startRow().intValue(),page.getSize());
        for (Task task : tasks) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
            if(processInstance == null){
            	continue;
            }
            String businessKey = processInstance.getBusinessKey();
            if (businessKey == null) {
                continue;
            }
            Candidate position = candidateRepository.findOne(Long.parseLong(businessKey));
            if (position == null) {
                continue;
            }
            mav.addObject("processInstance", processInstance);
            position.setTask(task);
            position.setProcessInstanceId(processInstanceId);
            leaves.add(position);
        }
        page.setTotalRecord(taskQuery.count());
        page.setItems(leaves);
        mav.addObject("page", page);
        return mav;
    }
    

    /**
     * 读取详细数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "detail/{id}")
    @ResponseBody
    public Candidate getCandidate(@PathVariable("id") Long id) {
    	Candidate position = candidateRepository.findOne(id);
        return position;
    }

    /**
     * 读取详细数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "detail-with-vars/{id}/{taskId}")
    @ResponseBody
    public Map<String, Object> getPositionWithVars(@PathVariable("id") Long id, @PathVariable("taskId") String taskId) {
    	Candidate position = candidateRepository.findOne(id);
        Map<String, Object> variables = taskService.getVariables(taskId);   
        variables.put("entity",position);
        return variables;
    }
    
    /**
     * 办理面试任务
     *
     * @param taskId
     * @return
     */
    @RequestMapping(value = "/task/complete/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String complete(@PathVariable("id") String taskId) {
        try {
            Map<String, Object> variables = new HashMap<String, Object>();
            variables.put("deptLeaderPass",true);
            variables.put("hrPass",true);
            taskService.complete(taskId,variables);
            return CommonUtils.msgCallback(true, "办理任务任务成功", "", null);
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "系统内部错误,请联系管理员，" + e.getMessage(), "", null);
        }
    }

}
